package com.itheima.controller;

import com.itheima.dto.GoodsDTO;
import com.itheima.dto.GoodsRequestDTO;
import com.itheima.dto.GoodsSkuDTO;
import com.itheima.pojo.*;
import com.itheima.qo.ItemSpuQuery;
import com.itheima.qo.PageQuery;
import com.itheima.vo.PageResult;
import com.itheima.vo.Result;
import com.itheima.service.BrandService;
import com.itheima.service.ItemCategoryService;
import com.itheima.service.ItemSpuService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequiredArgsConstructor
@RestController
@RequestMapping("/goods")
public class GoodsController {

    private final ItemSpuService itemSpuService;
    private final ItemCategoryService itemCategoryService;
    private final BrandService brandService;

    /**
     * 分页查询商品列表
     */
    @PostMapping("/spu/page")
    public Result page(@RequestBody PageQuery<ItemSpuQuery> pageQuery) {
        PageResult pageResult = itemSpuService.page(pageQuery);
        return Result.success(pageResult);
    }

    /**
     * 根据分类ID分页查询商品列表
     */
    @PostMapping("/spu/pageByCategory")
    public Result pageByCategory(@RequestBody PageQuery pageQuery,
                                 @RequestParam(required = false) Integer categoryId1,
                                 @RequestParam(required = false) Integer categoryId2,
                                 @RequestParam(required = false) Integer categoryId3) {
        PageResult pageResult = itemSpuService.pageByCategory(pageQuery, categoryId1, categoryId2, categoryId3);
        return Result.success(pageResult);
    }

    /**
     * 查询所有商品分类（树形结构）
     */
    @GetMapping("/category")
    public Result listCategories() {
        List<ItemCategory> categories = itemCategoryService.list();
        return Result.success(categories);
    }

    /**
     * 查询所有商品分类（列表结构）
     */
    @GetMapping("/category/list")
    public Result listAllCategories() {
        List<ItemCategory> categories = itemCategoryService.listAll();
        return Result.success(categories);
    }

    /**
     * 查询所有品牌
     */
    @GetMapping("/brand")
    public Result listBrands() {
        List<Brand> brands = brandService.listAll();
        return Result.success(brands);
    }

    /**
     * 根据ID查询商品详情
     */
    @GetMapping("/{id}")
    public Result getGoodsById(@PathVariable Long id) {
        GoodsDTO goods = itemSpuService.getById(id);
        return Result.success(goods);
    }

    /**
     * 添加商品
     */
    @PostMapping
    public Result addGoods(@RequestBody GoodsDTO goodsDTO) {
        // 添加调试日志
        System.out.println("=== 接收到添加商品请求 ===");
        System.out.println("原始请求数据: " + goodsDTO);
        if (goodsDTO != null) {
            System.out.println("商品标题: " + goodsDTO.getTitle());
            System.out.println("分类ID1: " + goodsDTO.getCategoryId1());
            System.out.println("分类ID2: " + goodsDTO.getCategoryId2());
            System.out.println("分类ID3: " + goodsDTO.getCategoryId3());
            System.out.println("描述: " + goodsDTO.getDescription());
            System.out.println("品牌ID: " + goodsDTO.getBrandId());
            System.out.println("供应商ID: " + goodsDTO.getSupplierId());
            if (goodsDTO.getSkus() != null) {
                System.out.println("SKU数量: " + goodsDTO.getSkus().size());
            }
        }

        System.out.println("开始保存商品数据");
        itemSpuService.save(goodsDTO);
        System.out.println("商品数据保存完成");
        return Result.success();
    }

    /**
     * 更新商品
     */
    @PutMapping
    public Result updateGoods(@RequestBody GoodsDTO goodsDTO) {
        // 添加调试日志
        System.out.println("=== 接收到更新商品请求 ===");
        System.out.println("原始请求数据: " + goodsDTO);

        itemSpuService.update(goodsDTO);
        return Result.success();
    }

    /**
     * 将GoodsRequestDTO转换为GoodsDTO
     */
    private GoodsDTO convertToGoodsDTO(GoodsRequestDTO requestDTO) {
        GoodsDTO goodsDTO = new GoodsDTO();
        goodsDTO.setId(requestDTO.getId());
        goodsDTO.setTitle(requestDTO.getName()); // name -> title
        goodsDTO.setDescription(requestDTO.getDescription());
        goodsDTO.setContent(requestDTO.getContent());

        // 设置分类ID
        if (requestDTO.getCategoryId() != null && !requestDTO.getCategoryId().isEmpty()) {
            if (requestDTO.getCategoryId().size() > 0) {
                goodsDTO.setCategoryId1(requestDTO.getCategoryId().get(0));
            }
            if (requestDTO.getCategoryId().size() > 1) {
                goodsDTO.setCategoryId2(requestDTO.getCategoryId().get(1));
            }
            if (requestDTO.getCategoryId().size() > 2) {
                goodsDTO.setCategoryId3(requestDTO.getCategoryId().get(2));
            }
        }

        // 设置品牌
        if (requestDTO.getBrand() != null && !requestDTO.getBrand().isEmpty()) {
            try {
                goodsDTO.setBrandId(Integer.parseInt(requestDTO.getBrand()));
            } catch (NumberFormatException e) {
                // 如果转换失败，保持brandId为null
            }
        }

        // 设置供应商名称
        goodsDTO.setSupplierName(requestDTO.getSupplierName());

        // 转换SKU信息
        if (requestDTO.getSpecList() != null && !requestDTO.getSpecList().isEmpty()) {
            List<GoodsSkuDTO> skus = requestDTO.getSpecList().stream().map(spec -> {
                GoodsSkuDTO sku = new GoodsSkuDTO();
                sku.setId(null); // 新增时ID应为null
                sku.setSkuCode(spec.getSpecCode());
                sku.setSkuName(spec.getSpecName());
                sku.setUnit(spec.getUnit());
                sku.setCode(spec.getBarcode());
                // 转换数值类型字段
                try {
                    sku.setProductWeight(spec.getWeight() != null ? Integer.valueOf(spec.getWeight()) : null);
                    sku.setProductLength(spec.getLength() != null ? Integer.valueOf(spec.getLength()) : null);
                    sku.setProductWidth(spec.getWidth() != null ? Integer.valueOf(spec.getWidth()) : null);
                    sku.setProductHeight(spec.getHeight() != null ? Integer.valueOf(spec.getHeight()) : null);
                    sku.setProductVolume(spec.getVolume() != null ? Integer.valueOf(spec.getVolume()) : null);
                } catch (NumberFormatException e) {
                    // 如果转换失败，保持为null
                }
                sku.setCost(spec.getCost());
                sku.setPrice(spec.getPrice());
                return sku;
            }).toList();
            goodsDTO.setSkus(skus);
        }

        // 设置单位信息
        goodsDTO.setLengthUnit(requestDTO.getLengthUnit());
        goodsDTO.setVolumeUnit(requestDTO.getVolumeUnit());
        goodsDTO.setWeightUnit(requestDTO.getWeightUnit());

        return goodsDTO;
    }

    /**
     * 删除商品
     */
    @DeleteMapping("/{id}")
    public Result deleteGoods(@PathVariable Long id) {
        itemSpuService.deleteById(id);
        return Result.success();
    }
}